package com.yint.http.response;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class Response
{
	private HttpURLConnection conn;
	private StringBuffer body;

	public Response( HttpURLConnection conn )
	{
		this.conn = conn;
	}

	public InputStream getStream() throws IOException
	{
		if ( conn == null )
		{
			return null;
		}
		return conn.getInputStream();
	}

	public StringBuffer body() throws IOException
	{
		if ( body == null )
		{
			body = new StringBuffer();
			try
			{
				if ( conn != null )
				{
					BufferedReader reader = new BufferedReader(
									new InputStreamReader( getStream() ) );
					String line = null;
					while ( ( line = reader.readLine() ) != null )
					{
						body.append( line );
					}
				}
			}
			catch ( IOException e )
			{
				body = null;
				throw e;
			}
		}
		return body;
	}

	public String getHeaderField( String key )
	{
		if ( conn == null )
		{
			return "";
		}
		return conn.getHeaderField( key );
	}

	public int getCode() throws IOException
	{
		if ( conn == null )
		{
			return -1;
		}
		return conn.getResponseCode();
	}

	public void close()
	{
		if ( conn != null )
		{
			conn.disconnect();
		}
	}

}
